import { API_BASE_URL, TIMEOUT, getToken , logout } from '../constant/index.js'
import { showToast } from '../utils/index.js'

// 请求拦截器
const requestInterceptor = (options) => {
	// 拼接基础URL
	if (!options.url.startsWith('http')) {
		options.url = API_BASE_URL[options.service || 'ENUM1'] + options.url
	}

	// 设置超时时间
	options.timeout = options.timeout || TIMEOUT

	// 设置默认header
	options.header = {
		'Content-Type': 'application/x-www-form-urlencoded',
		...options.header
	}

	// 添加token
	const token = getToken();
	if (token) {
		options.header.AccessToken = token;
	}

	return options
}

// 响应拦截器
const responseInterceptor = (response) => {
	const { statusCode, data } = response

	// 网络错误
	// if (!data) {
	// 	showToast('网络请求失败，请检查网络')
	// 	return Promise.reject(new Error('网络请求失败'))
	// }

	// HTTP错误状态码
	if (statusCode !== 200) {
		// 401 未授权，需要重新登录
		if (statusCode === 302) {
			logout()
			uni.showModal({
				title: "提示",
				content: "登录已过期，需重新登录，是否前往登录！",
				success: (res) => {
					if (res.confirm) {
						uni.navigateTo({url: "/pages/login/login"});
					} else {
						uni.switchTab({url: "/pages/index/index"});
					}
				},
			});
		} else {
			showToast(data.message || `请求错误: ${statusCode}`)
		}
		return Promise.reject(new Error(data.message || `HTTP Error: ${statusCode}`))
	}

	// 业务逻辑错误
	// if (data.code !== 0) {
	// 	showToast(data.message || '操作失败')
	// 	return Promise.reject(new Error(data.message || '业务逻辑错误'))
	// }

	return data
}

// 请求失败处理
const requestFail = (error) => {
	showToast('请求失败，请重试')
	console.error('请求失败:', error)
	return Promise.reject(error)
}

// 封装uni.request
const request = {
	get(url, data = {}, options = {}) {
		return this.request({
			url,
			data,
			method: 'GET',
			...options
		})
	},

	post(url, data = {}, options = {}) {
		return this.request({
			url,
			data,
			method: 'POST',
			...options
		})
	},

	put(url, data = {}, options = {}) {
		return this.request({
			url,
			data,
			method: 'PUT',
			...options
		})
	},

	delete(url, data = {}, options = {}) {
		return this.request({
			url,
			data,
			method: 'DELETE',
			...options
		})
	},

	request(options) {
		// 应用请求拦截器
		const requestOptions = requestInterceptor({
			...options
		})
		
		return new Promise((resolve, reject) => {
			uni.request({
				...requestOptions,
				timeout: 600000,
				success: (response) => {
					try {
						const result = responseInterceptor(response)
						resolve(result)
					} catch (error) {
						reject(error)
					}
				},
				fail: (error) => {
					try {
						requestFail(error)
					} finally {
						reject(error)
					}
				}
			})
		})
	}
}

export default request